package com.moxie.ocr.network;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.moxie.ocr.ocr.idcard.MXIDCardScan;
import com.moxie.ocr.ocr.utils.MD5Util;
import com.moxie.ocr.ocr.utils.MXConstants;
import com.moxie.ocr.ocr.utils.MXLog;
import com.moxie.ocr.ocr.utils.MXSDCardUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;


public class MXLicDownloadManager {
    private static String TAG = MXLicDownloadManager.class.getSimpleName();
    private static MXLicDownloadManager instance;
    private Context mContext;

    //是否是线上环境
    private boolean isProduction = false;

    private MXLicDownloadManager(Context context) {
        mContext=context;
    }

    public static MXLicDownloadManager getInstance(Context context) {
        if (instance == null) {
            synchronized (MXLicDownloadManager.class) {
                if (instance == null) {
                    instance = new MXLicDownloadManager(context);
                }
            }
        }
        return instance;
    }

    public boolean isProductionMode() {
        return isProduction;
    }

    public MXLicDownloadManager initWithProductionMode(boolean isProduction) {
        this.isProduction = isProduction;
        return this;
    }

    private String licSDCardPath;
    private MXLicenceModel licResult;

    /**
     * 下载最新License文件
     */
    public void downLoadLic() {
        this.licSDCardPath = MXIDCardScan.getInstance(mContext).getLicSDCardPath();
        String licenseUrl = "";
        if (isProduction){
            licenseUrl = MXConstants.LICENSE_PROD_INFO_URL;
        }else {
            licenseUrl = MXConstants.LICENSE_TEST_INFO_URL;
        }
        MXGetRequestUtils.getRequest(licenseUrl, new MXNetRequestCallback() {
            @Override
            public void completed(String response) {
                MXLog.i(TAG + "response:" + response);
                if (!TextUtils.isEmpty(response)) {
//                    licResult = JSON.parseObject(response, MXLicenceModel.class);
                    try {
                        JSONObject jsonObject = new JSONObject(response).optJSONObject("data");
                        licResult=new MXLicenceModel();
                        licResult.expired_time = jsonObject.optLong("expired_time");
                        licResult.start_time = jsonObject.optLong("start_time");
                        licResult.lic_url = jsonObject.optString("lic_url");
                        licResult.md5 = jsonObject.optString("md5");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (licResult != null)
                        downLoadLicContent(licResult.lic_url, licResult.md5);
                }
            }

            @Override
            public void failed(int httpStatusCode, String error) {
                super.failed(httpStatusCode, error);
                MXLog.i(TAG + "code:" + httpStatusCode + ";error:" + error);
            }
        });
    }

    private void downLoadLicContent(String url, final String md5) {
        MXGetRequestUtils.getRequest(url, new MXNetRequestCallback() {
            @Override
            public void completed(String response) {
                MXLog.i(TAG + "response:" + response);
                String md5Resp = MD5Util.MD5(response);
                if (TextUtils.equals(md5,md5Resp)) {
                    //保存license内容
                    saveLicFile(response);
                    Log.d("moxie===",response);
                } else {
                    MXLog.i(TAG + "md5校验失败");
                }
            }

            @Override
            public void failed(int httpStatusCode, String error) {
                super.failed(httpStatusCode, error);
                MXLog.i(TAG + "md5校验失败");
            }
        });
    }

    private void saveLicFile(final String response) {
        if (TextUtils.isEmpty(licSDCardPath)) {
            return;
        }
        String[] licPathSplit = licSDCardPath.split(File.separator);
        String licName = licPathSplit[licPathSplit.length - 1];
        File licFile = new File(licSDCardPath);
        String copyLicPath = "";
        if (licFile.exists()) {
            //licFile存在时，说明已经更新过license，并且license再次过期
            //此时将licPath目录下oldLicense备份到temp下，然后删掉oldLicense，将下载的newLicense保存到licPath目录下
            String copyLicDirectory = licFile.getParent() + File.separator + "temp";
            copyLicPath = copyLicDirectory + File.separator + licName;
            boolean copySuccess = MXSDCardUtils.copyFile(licSDCardPath, copyLicPath);
            if (copySuccess) {
                boolean deleteSuccess = licFile.delete();
                if (deleteSuccess) {
                    boolean saveSuccess = MXSDCardUtils.saveFile(licFile, response);
                    if (!saveSuccess) {
                        //如果保存失败，则需将备份还原
                        MXSDCardUtils.copyFile(copyLicPath, licSDCardPath);
                    }
                    //删除temp文件夹
                    MXSDCardUtils.deleteFile(new File(copyLicDirectory));
                }
            }
        } else {
            //licFile不存在时，直接将下载的newLicense保存到licPath目录下
            MXSDCardUtils.saveFile(licFile, response);
        }
    }
}
